package com.dzm.filter;

import com.dzm.constants.RedisConstant;
import com.dzm.properties.SecurityIgnoreProperties;
import com.dzm.utils.JwtUtil;
import com.dzm.utils.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Map;

/**
 * 作者：Dzm
 * 时间：2024-08-24-9:19
 * 功能：
 */

@Component
public class MyGlobalFilter implements GlobalFilter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private SecurityIgnoreProperties securityIgnoreProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest.Builder mutate = request.mutate();

        //白名单中的路径直接放行
        String path = request.getURI().getPath();
        if(securityIgnoreProperties.getWhites().contains(path)) {
            return chain.filter(exchange);
        }

        String authorization = request.getHeaders().getFirst("Authorization");
        String token = authorization.replaceFirst("Bearer ", "");

        Map<String, Object> claims = JwtUtil.parseToken(token);
        String uuid = (String) claims.get("user_key");
        String key = RedisConstant.LOGIN_TOKEN + uuid;
        Boolean hasKey = redisTemplate.hasKey(key);

        if(!hasKey) {
            return ResponseUtil.webFluxResponseWriter(response, "登录异常");
        }

        return chain.filter(exchange.mutate().request(mutate.build()).build());
    }
}
